import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import torchvision
import datetime

transform = transforms.Compose(
    [transforms.ToTensor(),
     transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

# 训练模型的超参数
input_size = 3072
output_size = 10
num_epochs = 50
batch_size = 64
learning_rate = 0.001

train_dataset = torchvision.datasets.CIFAR10(root='./data', train=True,
                                             download=True, transform=transform)

test_dataset = torchvision.datasets.CIFAR10(root='./data', train=False,
                                            download=True, transform=transform)

train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
                                           batch_size=batch_size,
                                           shuffle=True)

test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
                                          batch_size=batch_size,
                                          shuffle=False)

# 线性层的建立
model = nn.Linear(input_size, output_size)

# 损失函数和优化算法
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)

# train_loader的大小，也就是含有多少个bach。
total_step = len(train_loader)
# 训练模型
# 在整个数据集上迭代的次数
for epoch in range(num_epochs):
    starttime = datetime.datetime.now()
    # 每次取一个bach进行训练。
    for i, (images, labels) in enumerate(train_loader):
        # 将数据reshape到模型需要的大小。
        images = images.reshape(-1, 3 * 32 * 32)
        # 前向传播
        outputs = model(images)
        # 计算模型的loss
        loss = criterion(outputs, labels)
        # 后向传播，更新模型参数
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        if (i + 1) % 782 == 0:
            print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
                  .format(epoch + 1, num_epochs, i + 1, total_step, loss.item()))
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        images = images.reshape(-1, 3 * 32 * 32)
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum()
    print('Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total))